#!/bin/bash
# check_oh_mini_app.sh v1.0
# eg: ./check_oh_mini_app.sh ./haps/testdemo.hap

FILENAME=$1

# check file name is xxx.hap
if [[ $FILENAME != *.hap ]]; then
    echo "$FILENAME is not hap file"
    exit 1
fi

HAP_FILE=$(basename $1)
APP_NAME=${HAP_FILE%.*}
TMP_SUFFIX=`mktemp -u XXX`
TMP_DIR="hap_pack"

SCRIPT_PATH=$(dirname "$(realpath "$0")")
echo "script path is $SCRIPT_PATH"

SIGN_APP_ROOT_DIR="${SCRIPT_PATH}/sign_app_dir"
SIGN_APP_DIR="${SIGN_APP_ROOT_DIR}/${APP_NAME}_${TMP_SUFFIX}"
CP_HAP_PATH="${SIGN_APP_DIR}/${HAP_FILE}"

if [ ! -d "$SIGN_APP_ROOT_DIR" ]; then
    mkdir -p "$SIGN_APP_ROOT_DIR"
fi

if [ ! -d "$SIGN_APP_DIR" ]; then
    mkdir -p "$SIGN_APP_DIR"
else
    rm -rf "$SIGN_APP_DIR"
    mkdir -p "$SIGN_APP_DIR"
fi

cp $1 ${CP_HAP_PATH}

# unpacking the hap to directory
echo "unpacking ${CP_HAP_PATH} to ${SIGN_APP_DIR}/${TMP_DIR}"
java -jar "${SCRIPT_PATH}/app_unpacking_tool.jar" --mode hap --hap-path "${CP_HAP_PATH}" --out-path "${SIGN_APP_DIR}/${TMP_DIR}"

if [ ! -d "${SIGN_APP_DIR}/${TMP_DIR}/assets" ]; then
    echo "$FILENAME doesn't contain the assets folder"
    exit 2
fi

if [ ! -d "${SIGN_APP_DIR}/${TMP_DIR}/assets/entry" ]; then
    echo "$FILENAME doesn't contain the assets/entry folder"
    exit 3
fi

if [ ! -d "${SIGN_APP_DIR}/${TMP_DIR}/assets/js" ]; then
    echo "$FILENAME doesn't contain the assets/js folder"
    exit 4
fi

# clear
echo "remove dir ${SIGN_APP_DIR}"
rm -rf ${SIGN_APP_DIR}

echo "$FILENAME is valid hap file"
exit 0